package org.wk.news.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wk.core.common.view.ResponseVo;
import org.wk.news.dao.NewsManageDao;
import org.wk.news.dao.NewsPraiseDao;
import org.wk.news.domain.NewsManage;
import org.wk.news.domain.NewsPraise;
import org.wk.news.enums.ResponseCode;


@Service
public class NewsPraiseServiceImpl implements NewsPraiseService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private NewsPraiseDao newsPraiseDao;

    @Autowired
    private NewsManageDao newsManageDao;

    /**
     * 增加点赞状态
     *
     * @param userId 点赞人
     * @param newsId  点赞的新闻ID
     * @return
     */
    @Override
    public ResponseVo addPraise(String userId, String newsId) {
        if (selectPraise(userId, newsId)) {
            return ResponseVo.success();
        }
        NewsManage newsManage = newsManageDao.getOne(newsId);
        if (newsManage==null) {
            return new ResponseVo(ResponseCode.NEWS_NOT_EXIST);
        }
        newsManage.setPraiseNum(newsManage.getPraiseNum()+1);
        newsManageDao.update(newsManage);
        NewsPraise newsPraise = new NewsPraise();
        newsPraise.setUserId(userId);
        newsPraise.setNewsId(newsId);
        newsPraiseDao.save(newsPraise);
        return ResponseVo.success();
    }

    /**
     * 取消点赞状态
     *
     * @param userId 点赞人
     * @param newsId  点赞的新闻ID
     * @return
     */
    @Override
    public ResponseVo cancelPraise(String userId, String newsId) {
        NewsPraise newsPraise = newsPraiseDao.findByUserIdAndNewsId(userId, newsId);
        if (newsPraise!=null) {
            newsPraiseDao.delete(newsPraise);
            NewsManage newsManage = newsManageDao.getOne(newsId);
            if (newsManage==null) {
                return new ResponseVo(ResponseCode.NEWS_NOT_EXIST);
            }
            newsManage.setPraiseNum(newsManage.getPraiseNum()-1);
            newsManageDao.update(newsManage);
        }
        return ResponseVo.success();
    }

    /**
     * 查询点赞状态
     *
     * @param userId 点赞人
     * @param newsId  点赞的新闻ID
     * @return
     */
    @Override
    public boolean selectPraise(String userId, String newsId) {
        NewsPraise newsPraise = newsPraiseDao.findByUserIdAndNewsId(userId, newsId);
        return newsPraise!=null;
    }
}
